package org.hrqing.authorization.rest;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.hrqing.authorization.security.SecurityUser;
import org.hrqing.authorization.security.SecurityUtils;
import org.hrqing.authorization.utils.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.Map;

/**
 * @auther Hrqing
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class UserInfoApi {

    @SuppressWarnings("unchecked")
    @GetMapping(value = "/userinfo")
    public ResponseEntity<Map<String, Object>> getUserInfo() {
        Authentication authentication = SecurityUtils.getAuthentication();
        if (authentication == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "Invalid token"));
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails || principal instanceof OAuth2User) {
            Map<String, Object> convert = JSON.convert(principal, Map.class);
            convert.remove("@class");
            convert.remove("password");
            convert.remove("attributes");
            return ResponseEntity.ok(convert);
        }
        return ResponseEntity.ok(JSON.convert(principal, Map.class));
    }
}
